<!--
 * @Author: 蒋好东
 * @Date: 2023-08-28 10:54:49
 * @LastEditTime: 2023-08-28 14:09:08
 * @FilePath: \tcdm-process-console\src\views\eqpt\visual\index.vue
-->
<template>
  <layout-card
    v-model="search"
    :filters="issearchOptions"
    headline="信息列表"
    headtitle="数据筛选"
    :hasButton="true"
    @search-change="getData('search')"
    @search-reset="searchReset"
    class="layCard"
  >
    <!-- 基础按钮 -->
    <template #action>
      <el-button type="primary" @click="handleCreate('tips')"
        >维护提醒</el-button
      >
      <el-button
        type="primary"
        @click="handleCreate('export')"
        :disabled="tabledata?.length === 0"
        >导出</el-button
      >
      <el-button type="primary" @click="handleCreate('download')"
        >模版下载</el-button
      >
      <el-upload
        style="display: inline-block; margin-left: 12px; margin-right: 12px"
        ref="upload"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleImport"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="handleCreate('add')"
        >新增设备</el-button
      >
    </template>
    <!-- 数据表格 -->
    <table-common
      stripe="true"
      :columns="mapListColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="tabledata"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
      @sort-change="sortChange"
    >
      <!-- 维护图标提示 -->
      <template #eqptCode="{ row }">
        <img
          src=""
          width="12"
          height="12"
          v-if="row['reminder'] === '1'"
          style="background-color: red" />
        {{ row['eqptCode'] }}
      </template>
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button
          class="link-btn"
          @click="handleMaintenance(row)"
          link
          type="primary"
          >维护</el-button
        >
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary"
          >编辑</el-button
        >
        <el-popconfirm
          title="是否删除?"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="() => DeletRow(row)"
        >
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <!-- 维护提醒的窗口 -->
  <edit-dialog
    class="maintenance"
    :centerDialogVisible="tipsDialogVisible"
    :tilte="dialogTitle"
    :key="timer"
    :defaultButton="false"
    :width="'500'"
    @cancel="handleCancel"
  >
    <template #content>
      <filter-bar
        :filters="ismaintenanceTipOptions"
        ref="FilterRef"
        :hasButton="false"
        :hasTableButton="false"
        :multiple="''"
        :icon="false"
        :modelValue="''"
      />
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 新增设备地图窗口 -->
  <edit-dialog
    :centerDialogVisible="mapDialogVisible"
    :tilte="dialogTitle"
    :key="timer"
    :defaultButton="false"
    :width="'950'"
    @cancel="handleCancel"
  >
    <template #content>
      <div style="width: 100%; height: 500px; border: 1px solid #000">
        <map-control @mapClick="mapClick" @mapLoad="mapLoadEvent"></map-control>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" type="primary" @click="handleNext"
          >下一步</el-button
        >
        <el-button class="buttonOk" @click="handleSkip" plain>跳过</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 新增设备保存信息窗口 -->
  <edit-dialog
    class="edit"
    :centerDialogVisible="saveDialogVisible"
    :tilte="dialogTitle"
    :key="timer"
    :defaultButton="false"
    :width="'950'"
    @cancel="handleCancel"
  >
    <template #content>
      <filter-bar
        :filters="isdialogOptions"
        :hasButton="false"
        :rules="rules"
        ref="FilterRef"
        :hasTableButton="false"
        :multiple="''"
        :icon="false"
        :modelValue="''"
      />
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" @click="handleBack">返回</el-button>
        <el-button class="buttonOk" type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 维护信息窗口 -->
  <edit-dialog
    class="repair"
    :centerDialogVisible="maintenanceDialogVisible"
    :tilte="dialogTitle"
    :key="timer"
    :defaultButton="false"
    :width="'950'"
    @cancel="handleCancel"
  >
    <template #content>
      <filter-bar
        :filters="isrepairDialogOptions"
        :hasButton="false"
        :rules="rules"
        ref="FilterRef"
        :hasTableButton="false"
        :multiple="''"
        :icon="false"
        :modelValue="''"
      />
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button
          class="buttonOk"
          type="primary"
          @click="handleMaintenanceSave"
          >保存</el-button
        >
      </span>
    </template>
  </edit-dialog>
</template>

<script setup lang="ts">
import { toRaw, ref, computed, reactive, onBeforeMount } from "vue";

import { mapListColumns } from "@/views/eqpt/maintenanceRecords/config/columns";
import {
  searchOptions,
  dialogOptions,
  repairDialogOptions,
  maintenanceTipOptions,
  changeChildrenObj
} from "@/views/eqpt/maintenanceRecords/config/filters";
// import { getResource, postResource } from '@/api/resource'
import { useStore } from "vuex";
// 页面分布控件
import LayoutCard from "@/components/LayoutCard/index.vue";
// 表格控件
import TableCommon from "@/components/TableCommon/index.vue";
// 弹出框控件
import editDialog from "@/components/editDialog/index.vue";
// element-plusUI控件
import {
  FormRules,
  ElMessage,
  ElMessageBox,
  UploadInstance,
} from "element-plus";
// 表单控件
import FilterBar from "@/components/FilterBar/index.vue";
// 地图控件
import { image } from "@/assets/index";
import mapControl from "@/components/map/index.vue";
import { store } from "@/components/map/mapStore";
// API
import {
  maintenanceModuleDown,
  maintenancePageList,
  maintenanceDeleteRow,
  exportMaintenancePageList,
  maintenanceUpdata,
  maintenanceImport,
  getFindDeviceTypeTree,
  maintenanceTips,
  getUserInfo,
  maintenanceRecordsUpdata,
  maintenanceSave,
  uploadFiles
} from "@/api/eqpt/maintenanceRecords";
import { getResource } from "@/api/resource";

// 查询数据泛型接口
interface Serach {
  deviceCode: string;
  deviceType: string;
  userDepartment: string;
  homeUnit: string;
  terminal: object;
  lastMaintenanceTime: string[];
  equipmentType: string;
  maintenanceExecutor: string;
  maintenanceContent: string;
}

const stores = useStore();
const organTree = stores.state.user.organTree; // 获取树
const maplist = new Map();
// 数据筛选表单参数
const isdialogOptions = ref(dialogOptions);
const issearchOptions = ref(searchOptions);
const ismaintenanceTipOptions = ref(maintenanceTipOptions);
const isrepairDialogOptions = ref(repairDialogOptions);
// 数据加载效果参数
const loading = ref(false);
// 分页和数据展示参数
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tabledata = ref([]);
const search = ref<Serach>();
const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  pageCount: Math.ceil(total.value / pageSize.value),
}));
// 存放需要维护提醒的 id参数
// const remindList = ref([])

// 窗口的显示与隐藏的参数
const tipsDialogVisible = ref(false);
const mapDialogVisible = ref(false);
const saveDialogVisible = ref(false);
const maintenanceDialogVisible = ref(false);
// 窗口的标题的参数
const dialogTitle = ref("");
// 窗口时间参数
const timer = ref();
// 地图坐标参数
const mapPoint = ref({
  longitude: "",
  latitude: ""
});
// 窗口字段参数
const FilterRef = ref();
// 窗口显示状态参数
const dialogState = ref("");
// 校验规格参数
const validateRule = ref(true);
// 地图信息参数
const eqptId = ref("");

// 导入字段参数
const name = ref("");
const userId = ref("");
const organId = ref("");
const organName = ref("");
const btnImportLoading = ref(false); // 导入按钮加载状态
const CacheState = JSON.parse(
  window.localStorage.getItem("CacheState") as string
);
name.value = CacheState.user.userInfo.name;
userId.value = CacheState.user.userInfo.userId;
organId.value = CacheState.user.userInfo.organId;
organName.value = CacheState.user.userInfo.organName;
const upload = ref<UploadInstance>();
// 字典参数
const organNameList = reactive<any>([]);
const organNameListChild = reactive<any>([]);

/**
 * @functionName 分页、排序功能
 * @author 蒋好东
 * @date 2023-08-08 17:46:09
 * @version V1.0.0
 */
const changeCurrent = (value: number) => {
  current.value = value;
  getData();
};
const changePageSize = (size: number) => {
  pageSize.value = size;
  getData();
};
const order = ref([
  {
    column: "eqptCode",
    method: "asc",
  },
  {
    column: "lastMaintenanceTime",
    method: "asc",
  },
  {
    column: "maintenanceCycle",
    method: "asc",
  },
  {
    column: "terminal",
    method: "asc",
  },
  {
    column: "floor",
    method: "asc",
  },
]);

/**
 * @functionName 清空
 * @author 蒋好东
 * @date 2023-08-28 14:44:54
 * @version V1.0.0
 * @return
 */
const searchReset = (data: Serach) => {
  search.value = data;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData();
};

/**
 * @functionName 获取数据
 * @author 蒋好东
 * @date 2023-08-28 14:43:32
 * @version V1.0.0
 * @return
 */
const getData = async (...types: any[]) => {
  loading.value = true;
  const res = toRaw<any>(
    await maintenancePageList(JSON.stringify(searchData()))
  );
  if (res.code === "1") {
    loading.value = false;
    tabledata.value = res.data?.list;
    total.value = res.data?.total;
  } else {
    ElMessage.error("表格数据获取失败！");
  }
};

/**
 * @functionName 维护提醒、导出、模板下载、新增设备功能
 * @author 蒋好东
 * @date 2023-08-28 14:47:33
 * @version V1.0.0
 * @return
 */
const handleCreate = (type: string) => {
  timer.value = new Date().getTime();
  if (type === "tips") {
    // 维护提醒
    tipsDialogVisible.value = true;
    dialogTitle.value = "设置维护提醒";
    if (localStorage.getItem("maintenanceTipsTime")) {
      var tipsTime = JSON.parse(localStorage.getItem("maintenanceTipsTime"));
      ismaintenanceTipOptions.value.forEach((e: any) => {
        if (e.prop === "time") {
          e.defaultValue = tipsTime.time;
        }
        if (e.prop === "unit") {
          e.defaultValue = tipsTime.unit;
        }
      });
    }
  } else if (type === "export") {
    // 导出文档
    exportMaintenancePageList(searchData().condition)
      .then((res: any) => {
        excelDownloadExport({ name: "历史维护记录" + getDateNumber() }, res);
      })
      .catch(() => {
        ElMessage.error("导出失败");
      });
  } else if (type === "download") {
    // 导出模板
    maintenanceModuleDown()
      .then((res: any) => {
        excelDownloadExport({ name: "历史维护记录导入模板" }, res);
      })
      .catch(() => {
        ElMessage.error("导出模板失败");
      });
  } else {
    // 新增设施设备
    dialogState.value = "add";
    dialogTitle.value = "新增设施设备";
    backEditMapClick(isdialogOptions.value[14]?.events);
    isdialogOptions.value.forEach((e: any) => {
      e.defaultValue = "";
    });
    mapDialogVisible.value = true;
  }
};

/**
 * @functionName 维护提醒保存
 * @author 蒋好东
 * @date 2023-08-28 14:47:33
 * @version V1.0.0
 * @return
 */
 const handleSubmit = () => {
  const data = FilterRef.value.getParams();
  if (data.unit === undefined) {
    ElMessage.error("请选择维保单位");
  } else {
    const maintenanceData = data.time + (data.unit ?? "");
    maintenanceTips(maintenanceData)
      .then((res: any) => {
        if (res.code === "1") {
          tipsDialogVisible.value = false;
          const TipsTime = reactive<any>({
            time: data.time,
            unit: data.unit,
          });
          localStorage.setItem("maintenanceTipsTime", JSON.stringify(TipsTime));
          ElMessage.success("设置维护提醒时间成功！");
          getData();
        }
      })
      .catch((err: any) => {
        tipsDialogVisible.value = false;
        ElMessage.error("设置维护提醒时间失败！");
      });
  }
};

/**
 * @functionName 导入信息功能
 * @author 蒋好东
 * @date 2023-08-28 14:47:33
 * @version V1.0.0
 * @return
 */
const handleImport = (file: any) => {
  const index = file.name.lastIndexOf("."); // 根据文件名找到最后一个‘.’的索引
  const suffixName = file.name.substr(index); // 根据索引截取，得到后缀名
  if (suffixName !== ".xlsx" && suffixName !== ".xls") {
    ElMessage({
      message: "此文件不是excel文件",
      type: "warning",
    });
    upload.value?.clearFiles();
  } else {
    const formData = new FormData();
    formData.append("multipartFile", file.raw);
    formData.append("id", userId.value);
    formData.append("name", name.value);
    formData.append("organId", organId.value);
    formData.append("organName", organName.value);
    btnImportLoading.value = true;
    maintenanceImport(formData)
      .then((res: any) => {
        if (res.code === "1") {
          getData();
          ElMessage({
            message: "导入成功",
            type: "success",
          });
          upload.value?.clearFiles();
        } else {
          ElMessage.error(res.message);
          upload.value?.clearFiles();
        }
      })
      .catch((err: any) => {
        ElMessage.error(err.message);
        upload.value?.clearFiles();
      });
  }
};

/**
 * @functionName 保存新增信息功能
 * @author 蒋好东
 * @date 2023-08-29 10:58:52
 * @version V1.0.0
 */
const handleSave = async () => {
  validateRule.value = await FilterRef.value.validateRuleFormRef();

  if (!validateRule.value) {
    FilterRef.value.validateRuleFormRef();
  } else {
    const data = FilterRef.value.getParams();
    if (dialogState.value === "edit") {
      const editData = {
        ...getAddUpdateData(data),
        eqptId: eqptId.value,
        owner: undefined,
      };

      maintenanceRecordsUpdata(editData)
        .then((res: any) => {
          if (res.code === "1") {
            ElMessage.success("编辑成功！");
            handleCancel();
            getData();
          } else {
            ElMessage.error("编辑失败！");
          }
        })
        .catch((err: any) => {
          ElMessage.error(err);
        });
    } else {
      const addData = {
        ...getAddUpdateData(data),
        owners: undefined,
      };
      maintenanceSave(addData)
        .then((res: any) => {
          if (res.code === "1") {
            ElMessage.success("添加成功！");
            handleCancel();
            getData();
          } else {
            ElMessage.error("编辑失败！");
          }
        })
        .catch((err: any) => {
          ElMessage.error(err.message);
        });
    }
  }
};


// 返回文件数据信息
const getFiles = (...fileData: any) => {
  const files: Array<any> = [];
  if (fileData[0]) {
    const len = fileData[0].length;
    for (let i = 0; i < len; i++) {
      const ele: any = fileData[0][i];
      const fileName = ele.name;
      const index = fileName.lastIndexOf(".");
      const name = fileName.slice(0, index);
      const formData = new FormData();
      formData.append("file", ele.raw);
      formData.append("fileName", name);
      uploadFiles(formData).then((res: any) => {
        console.log(res);
        if (res.code === "1") {
          if (res?.data) {
            files.push({
              enclosureContent: res.data.enclosureContent, // 文件名 TCDM.md
              enclosureName: res.data.enclosureName, // 文件前缀 TCDM
              enclosureSuffix: res.data.enclosureSuffix, // 文件后缀md
              resourceAddress: res.data.resourceAddress, // 文件相对地址，网关地址+resourceAddres即可完成下载
              enclosureCode: res.data.enclosureCode, // 唯一标识
            });
            let maintenanceDatas = ref<any>();
            maintenanceDatas = {
              ...fileData[1],
              annex: files,
            };
            console.log(maintenanceDatas);

            saveMaintenance(maintenanceDatas);
          }
        } else {
          ElMessage.error(res.messages);
        }
      });
    }
  }
  return files;
};

/**
 * @functionName 保存维护信息功能
 * @author 蒋好东
 * @date 2023-08-29 10:58:52
 * @version V1.0.0
 */
 const handleMaintenanceSave = async () => {
  validateRule.value = await FilterRef.value.validateRuleFormRef();
  if (!validateRule.value) {
    FilterRef.value.validateRuleFormRef();
  } else {
    const data: any = FilterRef.value.getParams();

    const maintenanceData = reactive<any>({
      eqptId: eqptId.value,
      eqptCode: data.repairDeviceCode,
      annex: data.repairAttachments,
      file: data.repairMaintenanceContent,
      lastMaintenanceTime: data.repairLastMaintenanceTime,
      maintainer: data.repairMaintenanceExecutor,
      typeName: data.repairDeviceType,
    });

    let maintenanceDatas = ref<any>();
    if (data.repairAttachments === undefined) {
      maintenanceDatas = {
        ...maintenanceData,
      };
      saveMaintenance(maintenanceDatas);
    } else {
      getFiles(data.repairAttachments, maintenanceData);
    }
  }
};

const saveMaintenance = (data: any) => {
  maintenanceUpdata(data)
    .then((res: any) => {
      if (res.code === "1") {
        handleCancel();
        getData();
        ElMessage.success("更新记录设施设备维护内容成功！");
      }
    })
    .catch((err: any) => {
      ElMessage.error(err.message);
    });
};

/**
 * @functionName 取消功能
 * @author 蒋好东
 * @date 2023-08-08 17:55:02
 * @version V1.0.0
 */
const handleCancel = () => {
  timer.value = new Date().getTime()
  tipsDialogVisible.value = false
  mapDialogVisible.value = false
  saveDialogVisible.value = false
  maintenanceDialogVisible.value = false
  eqptId.value = ""
  mapPoint.value.latitude = ""
  mapPoint.value.longitude = ""
  isdialogOptions.value.forEach((e: any) => {
    e.defaultValue = ""
  })
  isrepairDialogOptions.value.forEach((e: any) => {
    e.defaultValue = ""
  })
  issearchOptions.value.forEach((e: any) => {
    e.defaultValue = ""
  })
  getData()
};

/**
 * @functionName 点击下一步功能
 * @author 蒋好东
 * @date 2023-08-08 17:55:02
 * @version V1.0.0
 */
const handleNext = () => {
  mapDialogVisible.value = false;
  saveDialogVisible.value = true;
};

/**
 * @functionName 点击返回功能
 * @author 蒋好东
 * @date 2023-08-08 17:55:02
 * @version V1.0.0
 */
const handleBack = async () => {
  saveDialogVisible.value = false;
  mapDialogVisible.value = true;
  isdialogOptions.value.forEach((e: any) => {
    if (e.prop === "coordinate" && mapPoint.value.longitude !== "") {
      e.defaultValue = `${mapPoint.value.longitude},${mapPoint.value.latitude}`;
      store.BNMap.removeGraphicsLayer("clickLayer");
      // 向地图添加临时图层
      const clickLayer = store.BNMap.creatGraphicsLayer({ id: "clickLayer" });
      clickLayer.removeAll();
      // 创建点
      const point = store.BNMap.createPoint({
        x: mapPoint.value.longitude,
        y: mapPoint.value.latitude,
        spatialReference: store.BNMap.spatialReference,
      });
      // store.BNMap.setCenter(point)
      // 创建图片
      const symbolStyle = store.BNSymbol.PictureMarkerSymbol(
        image.point,
        20,
        25
      );
      // 创建要素
      const picgraphic = store.BNMap.graphic(point, symbolStyle);
      // 添加到地图
      clickLayer.add(picgraphic);
      store.BNMap.addGraphicsLayer(clickLayer);
    }
  });
};

const handleSkip = async () => {
  mapDialogVisible.value = false;
  saveDialogVisible.value = true;
};

/**
 * @functionName 维护提醒信息,并回显信息功能
 * @author 蒋好东
 * @date 2023-08-29 10:55:02
 * @version V1.0.0
 */
const handleMaintenance = (row: any) => {
  eqptId.value = "";
  dialogTitle.value = "记录设施设备维护内容";
  eqptId.value = row.eqptId;
  maintenanceDialogVisible.value = true;
  isrepairDialogOptions.value.forEach((e: any) => {
    if (e.prop === "repairDeviceCode") {
      e.defaultValue = row.eqptCode;
    }
    if (e.prop === "repairDeviceType") {
      e.defaultValue = row.typeId;
    }
    if (e.prop === "repairMaintenanceExecutor") {
      e.defaultValue = row.maintainer;
      getExecutorOptions(row.ownerName).then(res =>{
        isrepairDialogOptions.value[4].inputProps.options = res;
      })
    }
    if (e.prop === "repairMaintenanceContent") {
      e.defaultValue = row.file;
    }
    if (e.prop === "repairLastMaintenanceTime") {
      e.defaultValue = row.lastMaintenanceTime;
    }
  });
};

const getDeviceTypeOptions = async (condition: any) =>{
  let paramName = {
      pageNum: 1,
      pageSize: 5000,
      condition: condition,
    }
    let DeviceData = ref([]) as any
    await getFindDeviceTypeTree(paramName).then((res: any) => {

      DeviceData.value = res.data.list
    })
    return DeviceData.value
}

const getExecutorOptions = async(ownerName : any) => {
  const organIds = ref("");
  organNameListChild.forEach((x: any) => {
    if (x.name === ownerName) {
      organIds.value = x.organId;
    }
  });
  const params = ref({
    groupIds: [] as any,
  });
  params.value.groupIds.length = 0;
  params.value.groupIds.push(organIds.value);

  const ExecutorData = ref([]) as any;
  await getUserInfo(params.value).then((resp) => {
    resp.data.forEach((d: any) => {
      const option = ref({
        label: d.userName,
        value: d.userName,
      });
      ExecutorData.value.push(option.value);
    });
  });

  return ExecutorData.value;
}
/**
 * @functionName 编辑,并回显信息功能
 * @author 蒋好东
 * @date 2023-08-29 10:55:02
 * @version V1.0.0
 */
const handleEdit = async (row: any) => {
  timer.value = new Date().getTime()
  dialogTitle.value = "编辑设施设备"
  eqptId.value = row.eqptId
  dialogState.value = "edit"
  saveDialogVisible.value = true
  backEditMapClick(isdialogOptions.value[14]?.events)

  setTimeout(()=> {
    console.log(row)
    let organs = []
    organNameList.forEach((key: any) => {
      if (row.useOrgans) {
        row.useOrgans.split(",").forEach((x: any) => {
          if (key.name === x) {
            organs = [key.name]
          }
        });
      } else {
        organs = []
      }
    })
    // 分解维护周期字符串
    let cycle = splitDigitsAndChinese(row.maintenanceCycle)
    mapPoint.value = row.coordinate

    //设备类型下拉回显
    let condition = {
        owners: [row.ownerId],
    }

    getDeviceTypeOptions(condition).then(res =>{
      changeChildrenObj(res)
      isdialogOptions.value[5].inputProps.data = res
      // FilterRef.value.setOptions("typeId", res)
    })


    //使用部门下拉框回显
    let organOptions = ref([]) as any
    organNameList.forEach((e : any) => {
      organOptions.value.push({value: e.name, label: e.name})
    })
    FilterRef.value.setOptions("useOrgans", organOptions.value)

    //维护执行人回显
    getExecutorOptions(row.ownerName).then(res =>{
      FilterRef.value.setOptions("maintainer", res)
    })

    FilterRef.value.setFieldsValue({
      eqptCode: row.eqptCode,
      eqptName: row.eqptName,
      eqptModel: row.eqptModel,
      typeId: row.typeId,
      useOrgans: organs,
      owner: row.ownerId,
      file: row.file,
      lastMaintenanceTime: row.lastMaintenanceTime,
      maintainer: row.maintainer,
      maintenanceCycle: cycle.digits,
      save: cycle.chinese,
      terminal: row.terminal,
      floor: row.floor,
      position: row.position,
      coordinate: row.coordinate.longitude + "," + row.coordinate.latitude
    })
  }, 100)
}

/**
 * @functionName 删除信息功能
 * @author 蒋好东
 * @date 2023-08-29 10:55:02
 * @version V1.0.0
 */
const DeletRow = async (row: any) => {
  maintenanceDeleteRow(row.eqptId)
    .then((res: any) => {
      if (res.code === "1") {
        getData();
        ElMessage.success("删除成功");
      } else {
        getData();
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      getData();
      ElMessage.error("删除失败");
    });
};

/**
 * @functionName 排序事件
 * @param {any} data 传入的某一列的列名和升降序
 * @author 蒋好东
 * @date 2023-08-17 17:48:41
 * @version V1.0.0
 * @return
 */
const sortChange = (data: any) => {
  const method = data.order === "ascending" ? "asc" : "desc";
  order.value[0].column = data.prop;
  order.value[0].method = method;
  getData();
};

/**
 * @functionName 地图点击
 * @author 彭庆南
 * @date 2023-08-08 17:55:02
 * @version V1.0.0
 */
const mapClick = (evt: any) => {
  mapDownImg(evt.mapPoint.x, evt.mapPoint.y, store.BNMap.spatialReference);
};

const mapLoadEvent = () => {
  console.log(mapPoint.value)
  if (mapPoint.value.latitude !== "") {
    store.BNMap.removeGraphicsLayer("clickLayer")
    // 向地图添加临时图层
    const clickLayer = store.BNMap.creatGraphicsLayer({ id: "clickLayer" })
    clickLayer.removeAll()
    // 创建点
    const point = store.BNMap.createPoint({
      x: mapPoint.value.longitude,
      y: mapPoint.value.latitude,
      spatialReference: store.BNMap.spatialReference,
    })
    store.BNMap.setCenter(point)
    // 创建图片
    const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 20)
    // 创建要素
    const picgraphic = store.BNMap.graphic(point, symbolStyle)
    // 添加到地图
    clickLayer.add(picgraphic)
    store.BNMap.addGraphicsLayer(clickLayer)
  }
};

const mapDownImg = (...points: any) => {
  console.log(...points);

  store.BNMap.removeGraphicsLayer("clickLayer");
  // 向地图添加临时图层
  const clickLayer = store.BNMap.creatGraphicsLayer({ id: "clickLayer" });
  clickLayer.removeAll();
  // 创建点
  const point = store.BNMap.createPoint({
    x: points[0],
    y: points[1],
    spatialReference: points[2],
  });
  // store.BNMap.setCenter(point)
  // 创建图片
  const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 25);
  // 创建要素
  const picgraphic = store.BNMap.graphic(point, symbolStyle);
  // 添加到地图
  clickLayer.add(picgraphic);
  store.BNMap.addGraphicsLayer(clickLayer);
  // 将相关信息保存到变量
  mapPoint.value.longitude = points[0].toFixed(4);
  mapPoint.value.latitude = points[1].toFixed(4);
  // 地图区域值暂时为空
  isdialogOptions.value.forEach((e: any) => {
    if (e.prop === "coordinate") {
      if (FilterRef.value) {
        FilterRef.value.setFieldsValue({
          coordinate: `${mapPoint.value.longitude} , ${mapPoint.value.latitude}`,
        });
        e.defaultValue = FilterRef.value.getParams().coordinate;
      } else {
        e.defaultValue = `${mapPoint.value.longitude} , ${mapPoint.value.latitude}`;
      }
    }
  });
};

/**
 * @functionName 返回重新点击地图的方法
 * @param {any} backClick 需要返回重新点击地图的参数
 * @description
 * @author 蒋好东
 * @date 2023-08-29 09:47:18
 * @version V1.0.0
 * @return
 */
const backEditMapClick = (backClick: any) => {
  backClick.click = (saveDialogVisible: any) => {
    if (mapPoint.value.latitude === "" && mapPoint.value.longitude === "") {
      saveDialogVisible.value = false;
      mapDialogVisible.value = true;
    } else {
      const mapClickVal = `(${mapPoint.value.longitude} , ${mapPoint.value.latitude})`;
      ElMessageBox.confirm(
        "当前坐标 : " + mapClickVal,
        "是否修改当前地图坐标?",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        saveDialogVisible.value = false;
        mapDialogVisible.value = true;
      });
    }
  };
};

// 查询数据封装
const searchData = () => {
  const getOrganData = (type: any) => {
    const organs = reactive<any>([]);
    if (type === "organs") {
      const Department =
        search.value?.userDepartment === undefined
          ? []
          : Object.values(search.value?.userDepartment);
      Department.forEach((organIds: any) => {
        organNameList.forEach((organ: any) => {
          if (organIds === organ.organId) {
            organs.push(organ.name);
          }
        });
      });
      return organs;
    } else if (type === "owners") {
      const HomeUnit =
        search.value?.homeUnit === undefined ? [] : [search.value?.homeUnit];
      HomeUnit.forEach((organIds: any) => {
        organNameListChild.forEach((organ: any) => {
          if (organIds === organ.organId) {
            organs.push(organ.name);
          }
        });
      });
      return organs;
    }
  };

  return {
    // 当前页
    pageNum: pager.value.currentPage,
    // 每页展示条数
    pageSize: pager.value.pageSize,
    condition: {
      // 字段排列顺序
      order: order.value,
      // 设备编号
      eqptCode: search.value?.deviceCode,
      // 设备型号
      eqptModel: search.value?.equipmentType,
      // 设备类型
      typeId: search.value?.typeId ?? undefined,
      // 使用部门
      organs:
        getOrganData("organs").length === 0
          ? undefined
          : [Object.values(getOrganData("organs"))[0]],
      // 归属单位
      owners:
        getOrganData("owners").length === 0
          ? undefined
          : [Object.values(getOrganData("owners"))[0]],
      // 航站楼
      terminals:
        search.value?.terminal === undefined
          ? []
          : Object.values(search.value?.terminal),
      // 维护执行人
      maintainer: search.value?.maintenanceExecutor,
      // 维护内容
      file: search.value?.maintenanceContent,
      // 末次维护时间
      startTime: Array.isArray(search.value?.lastMaintenanceTime)
        ? search.value?.lastMaintenanceTime?.length === 0
          ? ""
          : getStartDataTime(String(search.value?.lastMaintenanceTime[0]))
        : "",
      endTime: Array.isArray(search.value?.lastMaintenanceTime)
        ? search.value?.lastMaintenanceTime?.length === 0
          ? ""
          : getEndDataTime(String(search.value?.lastMaintenanceTime[1]))
        : "",
    },
  };
};

const getAddUpdateData = (data: any) => {
  const getsaveHomeUnit = (Unit: any) => {
    const isNum = /^[0-9]+$/;
    const HomeUnit = ref({
      id: "",
      name: "",
    });
    if (isNum.test(Unit)) {
      organNameListChild.forEach((e: any) => {
        if (e.organId === Unit) {
          HomeUnit.value.id = e.organId;
          HomeUnit.value.name = e.name;
        }
      });
      return HomeUnit.value;
    } else {
      organNameListChild.forEach((e: any) => {
        if (e.name === Unit) {
          HomeUnit.value.id = e.organId;
          HomeUnit.value.name = e.name;
        }
      });
      return HomeUnit.value;
    }
  };

  const getsaveOrgans = (Unit: any) => {
    const isNum = /^[0-9]+$/;

    const Organs = ref<any>([]);
    if (Unit === undefined) {
      return undefined;
    } else {
      if (isNum.test(Unit)) {
        organNameList.forEach((e: any) => {
          if (e.organId === Unit) {
            const Organ = {
              organId: e.organId,
              organName: e.name,
            };
            Organs.value.push(Organ);
          }
        });
        return Organs.value;
      } else {
        organNameList.forEach((e: any) => {
          if (e.name === Unit) {
            const Organ = {
              organId: e.organId,
              organName: e.name,
            };
            Organs.value.push(Organ);
          }
        });
        return Organs.value;
      }
    }
  };

  const saveData = {
    ...data,
    save: undefined,
    // 坐标
    coordinate: {
      longitude: data.coordinate.split(",")[0].trim(),
      latitude: data.coordinate.split(",")[1].trim(),
    },
    // 维护执行人
    maintainer: data.maintainer,
    // 维护期限
    maintenanceCycle:
      data.save === undefined ? undefined : data.maintenanceCycle + data.save,
    // 归属单位
    owner: toRaw(getsaveHomeUnit(data.owner)),
    owners: toRaw(getsaveHomeUnit(data.owner)),
    // 使用部门
    useOrgans:
      data.useOrgans === undefined
        ? undefined
        : toRaw(getsaveOrgans(data.useOrgans[0])),
    // 末次维护时间
    lastMaintenanceTime:
      data.lastMaintenanceTime === undefined
        ? undefined
        : getDataTime(data.lastMaintenanceTime),
    // : getDataTime(data.lastMaintenanceTime)
  };
  return saveData;
};

// 分割数字和汉字
const splitDigitsAndChinese = (text: any) => {
  if (text === undefined) {
    const digits = "";
    const chinese = "";
    return {
      digits,
      chinese,
    };
  } else {
    const digits = text.match(/\d+/g);
    const chinese = text.match(/[年月季度周日]+/g);
    return {
      digits: digits ? digits.join("") : "",
      chinese: chinese ? chinese.join("") : "",
    };
  }
};

/**
 * @functionName 导出文件方法封装
 * @param {any} fileName 文件名称
 * @param {any} exportDownloadData 下载文件流
 * @description
 * @author 蒋好东
 * @date 2023-08-29 09:47:18
 * @version V1.0.0
 */

const excelDownloadExport = (fileName: any, exportDownloadData: any) => {
  const blob = new Blob([exportDownloadData], {
    type: "application/vnd.ms-excel;charset=utf-8", // 文件格式
  });
  const link = document.createElement("a"); // 创建下载链接
  link.href = URL.createObjectURL(blob);
  link.download = `${fileName.name}.xlsx`;
  link.click();
  URL.revokeObjectURL(link.href);
  link.remove();
};

/**
 * @functionName 查询开始和结束时间格式封装
 * @param {any} dataTime. 需要格式化的时间
 * @description
 * @author 蒋好东
 * @date 2023-08-29 09:47:18
 * @version V1.0.0
 * @return 格式化后的时间
 */
const getStartDataTime = (dataTime: string) => {
  const date = new Date(dataTime);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return new Date(`${year}-${month}-${day} 00:00:00`);
};
const getEndDataTime = (dataTime: string) => {
  const date = new Date(dataTime);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return new Date(`${year}-${month}-${day} 23:59:59`);
};
// 返回时间字符串函数
const getDateNumber = () => {
  const date = new Date();
  return `${date.getFullYear()}${(date.getMonth() + 1)
    .toString()
    .padStart(2, "0")}${date.getDate().toString().padStart(2, "0")}`;
};
const getDataTime = (dataTime: string) => {
  const date = new Date(dataTime);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 周期
const validatorCycle = (rule: any, value: any, callback: any) => {
  const apr = /^(-|\+)?\d+(\d+)?$/;
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (apr.test(value) === false && value !== undefined) {
        callback(new Error("请输入正确的维护周期"));
      } else {
        callback();
      }
    }
  }
};
// 维护内容
const validatorFile = (rule: any, value: any, callback: any) => {
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (value?.length > 128) {
        callback(new Error("设备编号不能超过128位"));
      } else {
        callback();
      }
    }
  }
};

// 位置
const validatorPosition = (rule: any, value: any, callback: any) => {
  if (rule) {
    if (value === "") {
      callback();
    } else {
      if (value?.length > 128) {
        callback(new Error("位置不能超过128位"));
      } else {
        callback();
      }
    }
  }
};

// 表单校验
const rules = reactive<FormRules>({
  // 维护字段的校验
  repairDeviceCode: [{ required: true, message: "" }],
  repairDeviceType: [{ required: true, message: "" }],
  repairLastMaintenanceTime: [
    { required: true, message: "请选择末次维护时间", trigger: "change" },
  ],
  repairMaintenanceExecutor: [
    { required: true, message: "请选择维护执行人", trigger: "change" },
  ],
  // 新增字段的校验
  eqptCode: [
    { required: true, message: "请填写设备编号", trigger: "change" },
  ],
  typeId: [
    { required: true, message: "请选择设备类型", trigger: "change" },
  ],
  eqptName: [
    { required: true, message: "请填写设备名称", trigger: "change" },
  ],
  owner: [{ required: true, message: "请选择归属单位", trigger: "change" }],
  terminal: [
    { required: true, message: "请选择航站楼", trigger: "change" },
  ],
  coordinate: [
    {
      required: true,
      message: "请返回地图点击获取坐标",
      trigger: "change",
    },
  ],
  maintenanceCycle: [{ validator: validatorCycle, trigger: "change" }],
  file: [{ validator: validatorFile, trigger: "change" }],
  position: [{ validator: validatorPosition, trigger: "change" }],
});

// 获取terminal字典
const getTerminal = async (data: any) => {
  await getResource(data).then((res: any) => {
    issearchOptions.value.forEach((e: any) => {
      if (e.prop === "terminal") {
        e.inputProps.options = res.data.properties.meta;
      }
    });
  });
};



const getDeviceType = async () => {
  issearchOptions.value[1].inputProps.data = []
  getDeviceTypeOptions({}).then(res =>{
    changeChildrenObj(res)
    issearchOptions.value[1].inputProps.data = res
  })
};


/**
 * @functionName 树形选择
 * @description 作用于使用部门、归属单位
 * @author 蒋好东
 * @date 2023-08-29 09:47:18
 * @version V1.0.0
 * @return
 */
const organlist = () => {
  issearchOptions.value[1].inputProps.data = [];
  issearchOptions.value[2].inputProps.data = [];
  isdialogOptions.value[4].inputProps.data = [];
  issearchOptions.value[3].inputProps.data = [];
  isdialogOptions.value[1].inputProps.data = [];
  // 归属单位
  const processNode = (node: any) => {
    const type = reactive<any>({
      value: node.data.organId,
      label: node.data.name,
      children: [],
    });
    if (node.children) {
      node.children.forEach((child: any) => {
        const ctype = reactive<any>({
          value: child.data.organId,
          label: child.data.name,
          children: [],
        });
        if (child.children) {
          child.children.forEach((subChild: any) => {
            const cctype = reactive<any>({
              value: subChild.data.organId,
              label: subChild.data.name,
            });
            ctype.children.push(cctype);
            maplist.set(subChild.data.organId, subChild.data.organId);
          });
        }
        type.children.push(ctype);
        maplist.set(child.data.name, child.data.name);
      });
    }
    return type;
  };
  organTree.forEach((entry: any) => {
    issearchOptions.value[3].inputProps.data.push(processNode(entry));
    isdialogOptions.value[1].inputProps.data.push(processNode(entry));
  });
  // 使用部门
  if (organTree.length > 0) {
    organTree[0].children.forEach((organ: any) => {
      const organObject = reactive<any>({
        name: organ.data.name,
        organId: organ.data.organId,
      });
      organNameList.push(organObject);
    });
    organTree[0].children[0].children.forEach((organ: any) => {
      const organObject = reactive<any>({
        name: organ.data.name,
        organId: organ.data.organId,
      });
      organNameListChild.push(organObject);
    });
  }

  const getDepartment = (e: any) => {
    if (e.prop === "useOrgans" || e.prop === "userDepartment") {
      e.inputProps.options = [];
      organNameList.forEach((item: any) => {
        const organNameObj = reactive<any>({
          label: item.name,
          value: item.organId,
        });
        e.inputProps.options.push(organNameObj);
      });
    }
  };
  issearchOptions.value.forEach((e: any) => {
    getDepartment(e);
  });
  isdialogOptions.value.forEach((e: any) => {
    getDepartment(e);
  });
};

onBeforeMount(() => {
  getData();
  organlist();
  getDeviceType();
  getTerminal("terminal");
});
</script>

<style scoped>
.maintenance /deep/ .select-trigger {
  left: -172px;
  right: 20px;
  position: absolute;
  width: 100px;
}
.maintenance /deep/ .el-form-item__label {
  width: 110px !important;
}
.maintenance /deep/ .el-form-item {
  width: 250px !important;
  margin-left: 0.5px;
}
.maintenance /deep/ .select-trigger::after {
  content: "进行提醒";
  left: 110px;
  position: absolute;
  top: 0;
  width: 100px;
}
.layCard /deep/ .el-row {
  margin: 0 !important;
  font-size: 13px !important;
}
.layCard /deep/ .el-row .el-col {
  padding-left: 10px !important;
}
.layCard /deep/ .el-row .el-col .el-form-item .el-form-item__label {
  font-size: 13px;
  padding: 0;
  width: 0 !important;
}
.layCard
  /deep/
  .el-row
  .el-col:nth-child(5)
  .el-form-item
  .el-form-item__content
  .el-checkbox-group
  .el-checkbox
  .el-checkbox__label {
  font-size: 13px !important;
}
.layCard /deep/ .el-row .el-col:nth-child(5) .el-form-item {
  width: 251px !important;
}
.layCard
  /deep/
  .el-row
  .el-col:nth-child(6)
  .el-form-item
  .el-form-item__label {
  width: 93px !important;

  /* padding: 0; */
}
.layCard
  /deep/
  .el-row
  .el-col:nth-child(8)
  .el-form-item
  .el-form-item__label {
  width: 80px !important;

  /* padding: 0; */
}
.layCard /deep/ .el-row .el-col:last-child .el-form-item .el-form-item__label {
  width: 60px !important;
  /* padding: 0; */
}
.layCard /deep/ .button-group {
  margin: 0 0 96px;
}
.edit /deep/ .el-radio-group .el-badge:nth-child(2) .el-radio-button__inner {
  border-radius: 0 0.25rem 0.25rem 0;
}
.edit
  /deep/
  .el-row
  .el-col:nth-child(6)
  .el-form-item
  .el-form-item__content::after {
  content: "注：若找不到设备类型，请前往设备类型管理新增。";
  font-size: 14px;
  opacity: 0.5;
}
.edit /deep/ .el-row .el-col:nth-child(9) .el-form-item .el-form-item__label {
  padding: 0;
}
.edit /deep/ .el-row .el-col:nth-child(10) {
  padding-right: 0 !important;
}
.edit
  /deep/
  .el-row
  .el-col:nth-child(11)
  .el-form-item
  .el-form-item__content {
  right: 16px;
  position: absolute;
  width: 101px;
  padding: 0;
}
.repair /deep/ .el-row .el-col:nth-child(4) .el-form-item .el-form-item__label {
  padding: 0;
  width: 110px !important;
  margin-left: -10px;
}
.repair /deep/ .el-row .el-col:nth-child(5) .el-form-item .el-form-item__label {
  padding: 0;
  width: 110px !important;
  margin-left: -10px;
}
.repair
  /deep/
  .el-row
  .el-col:nth-child(6)
  .el-form-item
  .el-form-item__content {
  display: none;
}
</style>
